package com.gym.chatroom;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

/**
 * 客户端，需要有窗体对象
 * @author admin
 *
 */
@SuppressWarnings("all")
public class Client {
	//窗体对象
	private  JFrame frame;
	//多行文本框对象
	private  JTextArea textArea;
	//北部的面板对象
	private JPanel northPanel;
	//连接按钮和断开按钮
	private JButton btn_start;
	private JButton btn_stop;
	//中间的面板对象
	private JSplitPane centersplit;
	//南部的面板对象
	private JPanel southPanel;
	//发送消息的文本框
	private JTextField txtmes;
	//发送按钮
	private JButton btn_send;
	//左边的用户列表
	private JScrollPane leftUser;
	//右侧的消息区域
	private JScrollPane rightMes;
	//用户的服务器ip<单行文本框>
	private JTextField textHost;
	//端口
	private JTextField textPort;
	//用户名
	private JTextField textName;
	//用户列表组件
	private DefaultListModel listModel;
	//用户的实际实际列表对象
	private JList userList;
	//初始化窗体，并且设置格局
	private Socket socket;
	private PrintWriter printWriter;
	private BufferedReader bufferedReader;
	//全局标记，标记是否连接
	private boolean isConnect = false;
	//客户端用户列表
	private ArrayList<String> list = new ArrayList<String>();
	//自己的信息
	private String myInfo;
	//私聊按钮
	public Client() {
		//初始话窗体对象
		frame = new JFrame("客户端");
		textArea = new JTextArea();
		//设置多行文本框不能编辑
		textArea.setEditable(false);
		textPort = new JTextField("8888");
		textHost = new JTextField("127.0.0.1");
		textName = new JTextField("guanym");
		btn_start = new JButton("连接");
		btn_stop = new JButton("断开");
		btn_stop.setEnabled(false);
		listModel = new DefaultListModel();
		userList = new JList(listModel);
		northPanel = new JPanel();
		northPanel.setLayout(new GridLayout(1, 7));
		northPanel.add(new JLabel("服务器："));
		northPanel.add(textHost);
		northPanel.add(new JLabel("端口："));
		northPanel.add(textPort);
		northPanel.add(new JLabel("昵称："));
		northPanel.add(textName);
		northPanel.add(btn_start);
		northPanel.add(btn_stop);
		northPanel.setBorder(new TitledBorder("初始化信息"));
		rightMes = new JScrollPane(textArea);
		rightMes.setBorder(new TitledBorder("消息区域"));
		listModel.addElement("群聊");
		//设置选中群聊
		userList.setSelectedIndex(0);
		leftUser = new JScrollPane(userList);
		leftUser.setBorder(new TitledBorder("在线用户"));
		centersplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftUser, rightMes);
		centersplit.setDividerLocation(120);
		txtmes = new JTextField();
		btn_send = new JButton("发送消息");
		btn_send.setEnabled(false);
		southPanel = new JPanel(new BorderLayout());
		southPanel.add(txtmes,"Center");
		southPanel.add(btn_send,"East");
		southPanel.setBorder(new TitledBorder("发送消息"));
		frame.setLayout(new BorderLayout());
		frame.add(northPanel,"North");
		frame.add(centersplit, "Center");
		frame.add(southPanel,"South");
		//设置窗体大小
		frame.setSize(600, 400);
		frame.setLocationRelativeTo(null);;
		//窗口关闭时，应用程序结束
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//设置可见
		frame.setVisible(true);
		//监视窗口的事件
		frame.addWindowListener(new WindowListener() {
			
			@Override
			public void windowOpened(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void windowIconified(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void windowDeiconified(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void windowDeactivated(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void windowClosing(WindowEvent e) {
				try {
					//断开连接
					printWriter.println("DEL#"+myInfo);
					printWriter.flush();
					isConnect = false;
					textName.setEditable(true);
					textHost.setEditable(true);
					textPort.setEditable(true);
					btn_start.setEnabled(true);
					btn_stop.setEnabled(false);
					btn_send.setEnabled(false);
					socket.close();
					listModel.removeAllElements();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				JOptionPane.showMessageDialog(frame,"已经与服务器断开");
				
			}
			
			@Override
			public void windowClosed(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void windowActivated(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}
		});
		//点击连接的
		btn_start.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				String hoSt = textHost.getText().trim();
				int port =Integer.parseInt(textPort.getText().trim());
				String name = textName.getText().trim();
				frame.setTitle("一明聊天室"+name);
				if(connectServer(hoSt,port,name)){
					isConnect = true;
					textName.setEditable(false);
					textHost.setEditable(false);
					textPort.setEditable(false);
					btn_stop.setEnabled(true);
					btn_start.setEnabled(false);
					btn_send.setEnabled(true);
				}
			}
		});
		txtmes.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				int selectIndex = userList.getSelectedIndex();
				if(selectIndex==0){//群聊
					String meg ="【"+textName.getText()+"】"+":"+ txtmes.getText().trim().replaceAll("#","");
					if(meg!=null && !meg.equals("")){
						printWriter.println("ALL#"+meg);
					}
				}else{
					String privateName = (String)userList.getSelectedValue();
					String meg=txtmes.getText().trim().replaceAll("#","");
					if(meg!=null && !meg.equals("")){
						printWriter.println("PRI#"+privateName+"#"+meg);
					}
				}
				printWriter.flush();
				txtmes.setText("");
			}
		});
		//点击发送
		btn_send.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				int selectIndex = userList.getSelectedIndex();
				if(selectIndex==0){//群聊
					String meg ="【"+textName.getText()+"】"+":"+ txtmes.getText().trim().replaceAll("#","");
					if(meg!=null && !meg.equals("")){
						printWriter.println("ALL#"+meg);
					}
				}else{
					String privateName = (String)userList.getSelectedValue();
					String meg=txtmes.getText().trim().replaceAll("#","");
					if(meg!=null && !meg.equals("")){
						printWriter.println("PRI#"+privateName+"#"+meg);
					}
				}
				printWriter.flush();
				txtmes.setText("");
			}
		});
		//断开连接
		btn_stop.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					//断开连接
					printWriter.println("DEL#"+myInfo);
					printWriter.flush();
					isConnect = false;
					textName.setEditable(true);
					textHost.setEditable(true);
					textPort.setEditable(true);
					btn_start.setEnabled(true);
					btn_stop.setEnabled(false);
					btn_send.setEnabled(false);
					socket.close();
					listModel.removeAllElements();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
	}
	//连接服务器
	public boolean connectServer(String host,int port,String name){
		//创建socket对象
		try {
			 socket = new Socket(host, port);
			//写的对象
			printWriter = new PrintWriter(socket.getOutputStream());
			//读 的对象
			bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			printWriter.println(name);
			printWriter.flush();
			MesThread mesThread = new MesThread();
			mesThread.start();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(frame,"服务器连接失败，请确认信息是否填写正确！");
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public static void main(String[] args) {
		new Client();
	}
	//内部类，共享属性
	class MesThread extends Thread {
		@Override
		public void run() {
			String meg = null;
			String[] mes = null;
			while (true) {
				try {
					meg = bufferedReader.readLine();
					mes = meg.split("#");
					if(mes[0].equals("ADD")){//用户上线
						list.add(mes[1]);
						listModel.addElement(mes[1]);
					}else if(mes[0].equals("DEL")){//用户下线
						list.remove(mes[1]);
						listModel.removeElement(mes[1]);
					}else if(mes[0].equals("LIST")){//用户列表
						for(int i = 1;i<mes.length;i++){
						list.add(mes[i]);
						listModel.addElement(mes[i]);
						}
					}else if(mes[0].equals("INFO")){//保存客户端信息
						myInfo = mes[1];
					}else{
						textArea.append(meg+"\r\n");
						//设置滚动条
						textArea.setCaretPosition(textArea.getText().length());
					}
				} catch (IOException e) {
					JOptionPane.showMessageDialog(frame,"服务器异常！");
					return;
				}
			}
		}
	}
}
